package com.lagou.controller;

import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.pojo.LagouUser;
import com.lagou.service.AuthoCodeFeignClient;
import com.lagou.service.TokenService;
import com.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AuthoCodeFeignClient authoCodeFeignClient;

    /**
     * 用户注册
     * @param email
     * @param password
     * @param code
     * @return
     */
    @RequestMapping(value = "/register/{email}/{password}/{code}")
    public Integer register(@PathVariable(value = "email") String email,
                            @PathVariable(value = "password") String password,
                            @PathVariable(value = "code") String code) {
        System.out.println(email + ", " + password + ", " + code);

        //判断该邮箱是否已经注册
        Optional<LagouUser> byEmail = userService.findByEmail(email);
        if(byEmail != null && byEmail.isPresent()) {
            return 3;
        }

        // 验证验证码是否合法，如果合法，则注册成功
        Integer validate = authoCodeFeignClient.validate(email, code);
        if(validate != 0) {
            return 2;
        }

        //zhuce
        LagouUser lagouUser = new LagouUser();
        lagouUser.setEmail(email);
        lagouUser.setPassword(password);
        userService.insert(lagouUser);
        return 0;
    }

    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过，
     * false代表尚未注册
     * @param email
     * @return
     */
    @RequestMapping(value = "/isRegistered/{email}")
    public boolean isRegistered(@PathVariable(value = "email") String email) {
        return userService.findByEmail(email) == null ? false : true;
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和
     * 密码⽣成token，token存⼊数据库，并写⼊cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚
     * @param email
     * @return
     */
    @RequestMapping(value = "/login/{email}/{password}")
    public String login(@PathVariable(value = "email") String email,
                        @PathVariable(value = "password") String password,
                        HttpServletResponse response) {
        Optional<LagouUser> byEmail = userService.findByEmail(email);
        if(byEmail == null) {
            return "false";
        }
        if(password.equals(byEmail.get().getPassword())) {
            //登录成功
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            //把cookie写入到浏览器中：
            LagouToken lagouToken = new LagouToken();
            lagouToken.setEmail(email);

            long count = tokenService.count(lagouToken);
            if(count == 1) {
                LagouToken lagouToken1 = tokenService.find(lagouToken).get();
                //更新原来的token
                lagouToken1.setToken(token);
                tokenService.insert(lagouToken1);
            } else {
                lagouToken.setToken(token);
                tokenService.insert(lagouToken);
            }
            response.addCookie(cookie);
            return "true";
        }
        return "false";
    }

    /**
     * 根据token查询⽤户登录邮箱
     * @param token
     * @return
     */
    @RequestMapping(value = "/info/{token}")
    public String getEmailByToken(@PathVariable(value = "token") String token) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setToken(token);
        Optional<LagouToken> lagouToken1 = tokenService.find(lagouToken);
        if(lagouToken1 != null && lagouToken1.isPresent()) {
            return lagouToken1.get().getEmail();
        }
        return null;
    }
}
